<template lang="html">  
  <a-spin
    :spinning="loadingState.uploadImg"
    class="editor"
  >
    <div
      ref="toolbar"
      class="toolbar"
    />  
    <div
      ref="editor"
      class="text"
    /> 
    <div class="placeHolderWrap">
      <input
        ref="placeHolder"
        type="text"
        :placeholder="placeholder"
        :style="{border: 'none', background: '#fff', outline: 'none', width: '100%', color: '#ccc', margin: '0', height: '20px'}"
      >  
    </div> 
    <div
      v-if="isLimit"
      class="wordCount"
    >
      <span>{{ wordCountNum>=maxLength?maxLength:wordCountNum }}/{{ maxLength }}</span>
    </div>
  </a-spin>  
</template>  
  
<script>
import { uploadFile } from '@/api'
import E from 'wangeditor'
// import 'wangeditor/release/wangEditor.min.css'
import { getTextLength } from '@/utils/util'
import Vue from 'vue'

let overLength = false
let overHtmlLength = 0
export default {
  name: 'Editoritem',
  data() {
    return {
      // uploadPath,
      editor: null,
      info_: null,
      wordCountNum: 0,
      loadingState: {
        uploadImg: false
      }
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: {
      type: String,
      default: ''
    },
    isClear: {
      type: Boolean,
      default: false
    },
    maxLength: {
      type: Number,
      default: 10000
    },
    disabled: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: '请输入'
    },
    // 是否限制字数
    isLimit: {
      type: Boolean,
      default: false
    },
    // 附件上传的业务编码
    businessCode: {
      type: String,
      default: ''
    },
    // 是否启用自定义图片上传
    useCustomImg: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    isClear(val) {
      // 触发清除文本域内容
      if (val) {
        this.editor.txt.clear()
        this.info_ = null
      }
    },
    value: function (value) {
      if (value !== this.editor.txt.html()) {
        this.editor.txt.html(this.value)
      }
      let val = this.editor.txt.text().replace(/&nbsp;/gi, '')
      let newVal = val.replaceAll(' ', '')
      this.wordCountNum = newVal.length
      this.$refs.placeHolder.style.display = this.editor.txt.text().length !== 0 ? 'none' : 'block'
    },

    //value为编辑框输入的内容，这里我监听了一下值，当父组件调用得时候，如果给value赋值了，子组件将会显示父组件赋给的值
    disabled(val) {
      this.$nextTick(() => {
        // 设置富文编辑器是否禁用状态
        this.setState()
        // this.editor.$textElem.attr('contenteditable', !this.disabled)
      })
    }
  },
  mounted() {
    this.seteditor()
    this.editor.txt.html(this.value)
    this.$nextTick(() => {
      // 设置富文编辑器是否禁用状态
      this.setState()
    })
    this.$refs.placeHolder.style.display = this.editor.txt.text().length !== 0 ? 'none' : 'block'
  },
  methods: {
    /**
     * @description: 设置富文编辑器是否禁用状态
     */
    setState(){
      const disable = this.disabled ? 'disable' : 'enable'
      this.editor[disable]()
    },
    // 隐藏input输入框
    hidePlace() {
      this.$refs.placeHolder.style.display = 'none'
    },
    seteditor() {
      this.editor = new E(this.$refs.toolbar, this.$refs.editor)
      this.editor.config.uploadImgShowBase64 = true // base 64 存储图片
      // this.editor.config.uploadImgShowBase64 = false // base 64 存储图片
      this.editor.config.uploadImgServer = '' // 填写配置服务器端地址
      this.editor.config.uploadImgHeaders = {} // 自定义 header
      this.editor.config.uploadFileName = 'file' // 后端接受上传文件的参数名
      this.editor.config.uploadImgParams = {
        // 如果版本 <=v3.1.0 ，属性值会自动进行 encode ，此处无需 encode
        // 如果版本 >=v3.1.1 ，属性值不会自动 encode ，如有需要自己手动 encode
        file_type: 'img'
      }
      this.editor.config.height = 500 //设置编辑区高度为500px
      this.editor.config.uploadImgMaxSize = 2 * 1024 * 1024 // 将图片大小限制为 2M
      this.editor.config.uploadImgMaxLength = 6 // 限制一次最多上传 6 张图片
      this.editor.config.uploadImgTimeout = 3 * 60 * 1000 // 设置超时时间
      // 自定义 onchange 触发的延迟时间，默认为 200 ms
      this.editor.config.onchangeTimeout = 0 // 单位 ms
      // 隐藏�网络图片�tab
      this.editor.config.showLinkImg = false
      // 表情面板可以有多个 tab ，因此要配置成一个数组。数组每个元素代表一个 tab 的配置
      // this.editor.config.emotions = [
      //     {
      //         // tab 的标题
      //         title: '默认',
      //         // type -> 'emoji' / 'image'
      //         type: 'image',
      //         // content -> 数组
      //         content: [
      //             {
      //                 alt: '[坏笑]',
      //                 src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/50/pcmoren_huaixiao_org.png'
      //             },
      //             {
      //                 alt: '[舔屏]',
      //                 src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/40/pcmoren_tian_org.png'
      //             },
      //             {
      //                 alt: "[哈哈]",
      //                 src: "http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/8f/2018new_haha_org.png",
      //             },
      //         ]
      //     },
      //     {
      //         // tab 的标题
      //         title: 'emoji',
      //         // type -> 'emoji' / 'image'
      //         type: 'emoji',
      //         // content -> 数组
      //         content: ['😀', '😃', '😄', '😁', '😆']
      //     }
      // ],
      // 配置菜单
      this.editor.config.menus = [
        'head', // 标题
        'bold', // 粗体
        'fontSize', // 字号
        'fontName', // 字体
        'italic', // 斜体
        'underline', // 下划线
        'strikeThrough', // 删除线
        'foreColor', // 文字颜色
        'backColor', // 背景颜色
        'link', // 插入链接
        'list', // 列表
        'justify', // 对齐方式
        'quote', // 引用
        'image', // 插入图片
        'table', // 表格
        'video', // 插入视频
        'code', // 插入代码
        'undo', // 撤销
        'redo', // 重复
        'fullscreen' // 全屏
      ]
      // resultFiles 是 input 中选中的文件列表
      // insertImgFn 是获取图片 url 后，插入到编辑器的方法
      if (this.useCustomImg) {
        this.editor.config.customUploadImg = (resultFiles, insertImgFn) => {
          this.editor.enable()
          this.loadingState.uploadImg = true
          const formData = new FormData()
          formData.append('file', resultFiles[0])
          formData.append('businessCode', this.businessCode)
          uploadFile(formData)
            .then((res) => {
              // 设置富文编辑器是否禁用状态
              this.setState()
              // this.editor.$textElem.attr('contenteditable', !this.disabled)
              this.loadingState.uploadImg = false
              const token = Vue.getAcloudProvider().getAccessToken()
              const url = '/api/ycloud-file-center/oper/download?access_token=' + token + '&fileId=' + res.data.fileId
              insertImgFn(url)
            })
            .catch(() => {
              // 设置富文编辑器是否禁用状态
              this.setState()
              // this.editor.$textElem.attr('contenteditable', !this.disabled)
              this.loadingState.uploadImg = false
            })
        }
      }
      this.editor.config.onchange = (html) => {
        if (!this.isLimit) {
          this.info_ = html // 绑定当前逐渐地值
          this.$emit('change', this.info_) // 将内容同步到父组件中
          return
        }
        // 保留空格
        let val = this.editor.txt.text().replace(/&nbsp;/gi, '')
        let spaceLength = val.match(/\s/g)?.length
        // 去除空格
        let newVal = val.replaceAll(' ', '')
        if (!newVal) {
          this.$emit('change', '')
          return
        }
        this.wordCountNum = newVal.length
        if (newVal.length >= this.maxLength) {
          if (!overLength) {
            overHtmlLength = html.length
            overLength = true
          } else {
            // 去除收尾p标签
            let idx = spaceLength ? this.maxLength + spaceLength : this.maxLength
            let newHtml = html.substr(3, idx)
            this.$nextTick(() => {
              this.editor.txt.html(`<p>${newHtml}</p>`)
            })
            this.$message.error('输入字数超过限制字数')
          }
        } else {
          overLength = false
          this.info_ = html // 绑定当前逐渐地值
          this.$emit('change', this.info_) // 将内容同步到父组件中
        }
      }
      this.editor.config.onfocus = () => {
        this.$refs.placeHolder && (this.$refs.placeHolder.style.display = 'none')
      }
      this.editor.config.onblur = () => {
        this.$refs.placeHolder &&
          (this.$refs.placeHolder.style.display = this.editor.txt.text().length !== 0 ? 'none' : 'block')
      }
      // 创建富文本编辑器
      this.editor.create()
    }
  }
}
</script>  
  
<style lang="less" scoped>
.editor {
  width: 100%;
  margin: 0 auto;
  position: relative;
  z-index: 0;
  margin-bottom: 24px;
}
.toolbar {
  border: 1px solid #ccc;
}
.text {
  border: 1px solid #ccc;
  height: 600px;
  word-break: break-all;
  overflow: auto;
}
.wordCount {
  position: absolute;
  bottom: -33px;
  right: 5px;
}
.placeHolderWrap {
  position: absolute;
  left: 10px;
  top: 63px;
}
/deep/.w-e-text {
  overflow-y: auto;
}
</style>  